package com.bit.musicserver.Service;

import com.bit.musicserver.Tools.Constat;
import com.bit.musicserver.Tools.ResponseBodyMessage;
import com.bit.musicserver.mapper.LoveMusicMapper;
import com.bit.musicserver.mapper.MusicMapper;
import com.bit.musicserver.model.Music;
import com.bit.musicserver.model.User;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.apache.ibatis.binding.BindingException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Service
public class MusicService {
    @Value("${music.local.path}")  //获取配置文件中的信息
    private String SAVE_PATH /*= "E:/localMusic/Music/"*/;
    @Autowired
    private MusicMapper musicMapper;
    @Autowired
    private LoveMusicMapper loveMusicMapper;

    /*上传音乐*/
    public ResponseBodyMessage<Boolean> insertMusic(@RequestParam String singer,
                                                    @RequestParam("filename") MultipartFile file,
                                                    HttpServletRequest request, HttpSession httpSession) {
        //1.检查是否登成功
        HttpSession session = request.getSession(false);
        if (session == null || session.getAttribute("USERINDFO_SESSION_KEY") == null) {
            System.out.println("没有登录");
            return new ResponseBodyMessage<>(-1, "请登录上传", false);
        }


        //先查询数据库当前有没有这首歌(歌曲名+歌手)

        //2.上传到了服务器
        String fileNameANDType = file.getOriginalFilename();//获取文件名称  //获取的 xxx.mp3
        System.out.println("fileNameANDType:" + fileNameANDType); //获取并打印地址

        String path = SAVE_PATH + fileNameANDType;
        System.out.println("path:" + path);
        File dest = new File(path); //获取这个文目录
        if (!dest.exists()) {
            dest.mkdir(); //如果不存在就创建
        }
        //存在就上传文件
        try {
            file.transferTo(dest);  //上传文件
            // return new ResponseBodyMessage<>(0, "上传成功", true);
        } catch (IOException e) {
            e.printStackTrace();
            return new ResponseBodyMessage<>(-1, "服务器上传失败", false);
        }
        // return new ResponseBodyMessage<>(-1, "上传失败", false);

        //进行数据库的上传
        //1.准备需要的数据  2.调用insert

        int index = fileNameANDType.lastIndexOf(".");
        String title = fileNameANDType.substring(0, index);

        List<User> user = (List)session.getAttribute(Constat.USERINDFO_SESSION_KEY);
        User users = null;
        if (!user.isEmpty()) {
            users = user.get(0);
        }
        int userid = users.getId();
        //播放音乐发送的是Http请求
        String url = "Music/get?path=" + title;

        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd ");//获取时间
        String time = sf.format(new Date());

        try {
            int ret = 0;
            ret = musicMapper.insertMusic(title, singer, time, url, userid);
            if (ret == 1) {
                //这里应该跳转到音乐列表界面
                return new ResponseBodyMessage<>(0, "数据库上传成功", true);
            } else {
                return new ResponseBodyMessage<>(-1, "数据库上传失败", false);
            }
        } catch (BindingException e) {
            dest.delete(); //删除
            return new ResponseBodyMessage<>(-1, "数据库上传失败", false);
        }
    }


    /*播放音乐*/
    public ResponseEntity<byte[]> get(String path){  //ResponseEntity 这个和responsebody 用法类似
        File file = new File(SAVE_PATH + path);
        byte[] a = null;
        try {
            a = Files.readAllBytes(file.toPath());
            System.out.println(a);
            if (a==null){
                return ResponseEntity.badRequest().build();  //返回400状态码
            }
            return ResponseEntity.ok(a);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return ResponseEntity.badRequest().build();
    }


    /*删除单个音乐*/
    public ResponseBodyMessage<Boolean> deleteMusicById(@RequestParam("id") String id){
        //1，先检查音乐是否存在
        int iid  =Integer.parseInt(id);
        //2.如果存在进行删除
        Music music =  musicMapper.findMusicById(iid); //接收到这条数据
        if (music==null){
            System.out.println("没有这个id的音乐");
            return new ResponseBodyMessage<>(-1,"没有删除的音乐",false);
        }else {
            //2.1 删除数据库上的数据
            int ret =  musicMapper.deleteMusicById(iid);
            if (ret==1){
                //2.2 删除服务器上的数据
                int index = music.getUrl().lastIndexOf("=");
                System.out.println(index);
                String fileName =  music.getUrl().substring(index+1);//获取路径
                System.out.println("fileName:" + fileName );
                File file = new File(SAVE_PATH + fileName + ".mp3"); //获取文件路径
                System.out.println("当前路径"+file.getPath());

                if(file.delete()){
                    //删除音乐的时候同时要检查收藏音乐的表,并删除
                    loveMusicMapper.dateLoveMusicByMusicId(iid);
                    return new ResponseBodyMessage<>(0,"服务器音乐删除成功",true);
                }else {
                    return new ResponseBodyMessage<>(-1,"服务器音乐删除失败",false);
                }
            }else {
                return new ResponseBodyMessage<>(-1,"数据库当中的音乐没有删除成功",false);
            }
        }
    }



/*批量删除音乐*/
    public ResponseBodyMessage<Boolean> deleteMusicByUrl( @RequestParam("id[]") List<Integer> id){
        int sum=0;
        for (int i = 0; i < id.size(); i++) {
            Music music =  musicMapper.findMusicById(id.get(i));
            if (music==null){
                System.out.println("没有为id的音乐");
                return new ResponseBodyMessage<>(-1,"没有删除的音乐",false);
            }
            int ret =  musicMapper.deleteMusicById(id.get(i));
            if (ret==1){
                int index = music.getUrl().lastIndexOf("=");
                System.out.println(index);
                String fileName =  music.getUrl().substring(index+1);//

                File file = new File(SAVE_PATH + fileName + ".jpg");
                System.out.println("当前路径"+file.getPath());
                if(file.delete()){
                    //删除音乐的时候同时要检查收藏音乐的表,并删除
                    loveMusicMapper.dateLoveMusicByMusicId(id.get(i));
                    sum+=ret;
                    //return new ResponseBodyMessage<>(0,"服务器音乐删除成功",true);
                }else {
                    return new ResponseBodyMessage<>(-1,"服务器音乐删除失败",false);
                }
            }else {
                return new ResponseBodyMessage<>(-1,"数据库删除失败",false);
            }
        }
        if (sum== id.size()) {
            System.out.println("整体删除成功");
            return new ResponseBodyMessage<>(0,"音乐删除成功",true);
        }else {
            System.out.println("整体删除失败");
            return new ResponseBodyMessage<>(-1,"音乐删除失败",false);
        }
    }



/*查询音乐*/
    public ResponseBodyMessage<List<Music>> findMusic(@RequestParam(required = false) String musicName){
        List<Music> Musiclist = null;
        if(musicName!=null){
            Musiclist = musicMapper.findMusicName(musicName);
        }else {
            Musiclist = musicMapper.findMusic();
        }
        return new ResponseBodyMessage<>(0,"查询到音乐",Musiclist);
    }
}
